package com.nnxy.controller;


import com.nnxy.service.DeptService;
import com.nnxy.pojo.Dept;
import com.nnxy.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result list(){
        List<Dept> list=deptService.list();
        return new Result(1,"success",list);

    }
    @DeleteMapping
    public Result del(Integer id){

        // 检查部门下是否有员工
        boolean hasEmployees = deptService.hasEmployees(id);
        if (hasEmployees) {
            return new Result(0, "删除失败，该部门下有员工数据", null);
        }
        // 如果没有员工，执行删除操作
        deptService.removeById(id);
        return new Result(1, "success", null);
    }

    @PostMapping
    public Result add(@RequestBody Dept dept){
        try {
            deptService.add(dept);
            return new Result(1,"success",null);
        } catch (Exception e) {
            //返回失败数据
            return new Result(0,"fail,部门重复",null);
        }
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        Dept dept=deptService.findById(id);
        return new Result(1,"success",dept);
    }

    @PutMapping
    public Result update(@RequestBody Dept dept){
        try {
            deptService.modify(dept);
            return new Result(1,"success",null);
        } catch (Exception e) {
            return new Result(0,"修改失败,部门重复",null);
        }
    }
}
